package com.hyper_yang._05_juc.chap02;


import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 演示读写锁的锁降级
 *   什么是锁降级：`在当前线程拥有写锁的情况下，获取到读锁，随后释放写锁的过程就是锁降级
 */
public class LockDowngradingDemo {

    private int data = 0;
    private ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    private Lock readLock = readWriteLock.readLock();
    private Lock writeLock = readWriteLock.writeLock();

    //读   读读可并发
    public int readData(){
        readLock.lock();
        try {
            System.out.println("readData = " + data);
            return data;
        } finally {
            readLock.unlock();
        }
    }

    //写  写写不可并发     读写/写读 不可并发
    public void writeData(int newData){
        writeLock.lock();
        try {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            this.data = newData;
            readLock.lock(); //写锁释放前获取读锁。
        } finally {
            writeLock.unlock(); //获取读锁后释放写锁。
        }

        try {
            //接下来我还需要进行一些读操作。
            //int result = readData();
            //System.out.println("锁降级后得到 result = " + result);
            System.out.println("锁降级后得到 result = " + data);
        } finally {
            readLock.unlock();
        }
    }


    public static void main(String[] args) {
        LockDowngradingDemo demo = new LockDowngradingDemo();
        
        new Thread(()->{
            demo.writeData(1);
        },"A").start();
        
        new Thread(()->{
            int result = demo.readData();
            //System.out.println("result = " + result);
        },"B").start();
    }
}
